using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;

public class MapLevelUI : MonoBehaviour
{
    [SerializeField] private GameObject mapListGo;
    [SerializeField] private GameObject levelListGo;
    [SerializeField] private GameObject leveGridGo;

    [SerializeField] private List<MapUI> mapUIList;

    [SerializeField] private GameObject levelTemplatePrefab;

    public void ShowMapList(MapSO[] mapArray)
    {
        mapListGo.SetActive(true);
        levelListGo.SetActive(false);
        UpdateMapUIList(mapArray);
    }

    private void UpdateMapUIList(MapSO[] mapArray)
    {
        for (int i = 0; i < mapArray.Length; i++)
        {
            mapUIList[i].Show(mapArray[i].starNumberOfMap, this, i + 1); //从数据对象中取出数据显示到UI上
        }
    }

    public void OnMapButtonClick(int mapID)
    {
        LevelSelectManager.Instance.SetSelectedMap(mapID); //传入ID在LevelSelectManager中设置当前选中的地图
        ShowLevelGrid();
    }

    private void ShowLevelGrid()
    {
        mapListGo.SetActive(false);
        levelListGo.SetActive(true);

        int[] starNumberOfLevel = LevelSelectManager.Instance.GetSelectMap();
        foreach (Transform child in leveGridGo.transform)//foreach遍历了所有的孩子
        {
            Destroy(child.gameObject);
        }
        for (int i = 0; i < starNumberOfLevel.Length; i++)
        {
            GameObject go = GameObject.Instantiate(levelTemplatePrefab); //将模板进行实例化
            go.GetComponent<RectTransform>().SetParent(leveGridGo.transform); //将实例化后的物体放到levelGridGo中
            go.GetComponent<LevelUI>().Show(starNumberOfLevel[i], i + 1, this);
        }
    }

    public void OnLevelButtonClick(int levelID)
    {
        LevelSelectManager.Instance.SetSelectLevel(levelID);
    }
    
    
    public void OnReturnButtonClick()
    {
        mapListGo.SetActive(true);
        levelListGo.SetActive(false);
    }
}